package biz.almas.uycnr.crawler.crawler.timer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import biz.almas.uycnr.crawler.constant.Constant;
import biz.almas.uycnr.crawler.crawler.UYCNRParser;
import biz.almas.uycnr.crawler.crawler.downloder.UYCNRDownloader;
import biz.almas.uycnr.crawler.dao.AppendixDao;
import biz.almas.uycnr.crawler.dao.CnrDocumentDao;
import biz.almas.uycnr.crawler.entity.Appendix;
import biz.almas.uycnr.crawler.entity.Channel;
import biz.almas.uycnr.crawler.entity.CnrDocument;

public class KZCNRTimerTask extends AbstractTimerTask {

	private static List<CnrDocument> documents = new ArrayList<CnrDocument>();

	private static List<Appendix> appendixs = new ArrayList<Appendix>();

	private long currentTime;

	private UYCNRParser parser;

	private int langId = 4; // 4 表示哈文
	private String langShortName = "kz_";

	/**
	 * @param documents
	 * @param appendixs
	 * @param currentTime
	 */
	public KZCNRTimerTask() {
		super();
		this.currentTime = System.currentTimeMillis();
	}

	@Override
	protected void execute() throws IOException {
		String channelPath = download(Constant.CHANNEL_XML_URL_KZ,
				langShortName + currentTime, "index");
		parser = new UYCNRParser();

		if (parser.parseChannel(channelPath, langId)) {
			List<Channel> channels = parser.getChannels();
			for (Channel channel : channels) {
				parseChannelDocument(channel, langId);

				store(channel.getChnlId());

				documents.clear();
				appendixs.clear();
			}
			channels.clear();
		}

	}

	/**
	 * Ansar786 Nov 21, 2015
	 */
	private void store(int channelId) {
		if (documents != null && documents.size() > 0) {
			CnrDocumentDao documentDao = new CnrDocumentDao();
			documentDao.storeDocuments(documents, channelId, langId);
		}

		if (appendixs != null && appendixs.size() > 0) {
			AppendixDao appendixDao = new AppendixDao();
			appendixDao.storeAppendixs(appendixs);
		}
	}

	/**
	 * 解析栏目文档 Ansar786 Dec 12, 2015
	 * 
	 * @param channel
	 * @param langId
	 */
	private void parseChannelDocument(Channel channel, int langId) {
		for (int i = 0; i < 25; i++) {
			String documentPath;
			String docUrl = getUrl(channel.getDocumentsUrl(), i);
			try {
				documentPath = download(docUrl, langShortName + currentTime
						+ "/" + channel.getChnlId(), "document_" + i);
				if (parser.parseDocument(documentPath, langId)) {
					documents.addAll(parser.getDocuments());
					appendixs.addAll(parser.getAppendixs());
				}
			} catch (IOException e) {
				logger.error("文档下载时出错：" + docUrl);
			}
		}
	}

	private String download(String xmlUrl, String path, String fileName)
			throws IOException {
		return UYCNRDownloader.download(xmlUrl, path, fileName);
	}

	/**
	 * 每300秒执行一次
	 */
	@Override
	protected long period() {
		return 5 * 60 * 1000;
	}

	/**
	 * 
	 */
	@Override
	protected long delay() {
		// long delay;
		// Calendar today = Calendar.getInstance();
		// int day = today.get(Calendar.DAY_OF_YEAR);
		// int hour = today.get(Calendar.HOUR_OF_DAY);
		//
		// Calendar next = Calendar.getInstance();
		// next.set(Calendar.HOUR_OF_DAY, 7);
		// next.set(Calendar.MINUTE, 0);
		// next.set(Calendar.SECOND, 0);
		//
		// if(hour == 7){
		// delay = 0;
		// }else if((hour<7)){
		// next.set(Calendar.DAY_OF_YEAR, day);
		// delay =next.getTimeInMillis() - today.getTimeInMillis();
		// }else{
		// next.set(Calendar.DAY_OF_YEAR, day+1);
		// delay =next.getTimeInMillis() - today.getTimeInMillis();
		// }
		// logger.info("delay:" + delay);
		return 0;
	}

	private String getUrl(String url, int page) {
		StringBuffer result = new StringBuffer();

		if (page == 0) {
			return url;
		} else {
			result.append(url.substring(0, url.lastIndexOf(".")));
			result.append("_");
			result.append(page);
			result.append(".xml");
			return result.toString();
		}
	}

}
